#include "CServer.h"

int server_thread_func(void *caller)
{
	return ((CServer*) caller)->RunPolling(NULL);
}

CServer::CServer()
{	
	m_bServerstarted = false;
}

void CServer::SetCallbackGUI(IGUICallback* CallbackGUI)
{
	m_pConfigDialog = CallbackGUI;
}

CServer::~CServer()
{
	if(m_bServerstarted == false)
		return;
	RakNetworkFactory::DestroyRakPeerInterface(m_pServer);
	SDL_KillThread(m_pPollThread);
}

int CServer::RunPolling(void* data)
{
	Packet* packet;
	while (1)
	{
		packet=m_pServer->Receive();
		if (packet)
		{
			switch (packet->data[0])
			{
			case ID_REMOTE_DISCONNECTION_NOTIFICATION:
				m_pConfigDialog->UpdateServerLog("Another client has disconnected.\n");
				break;
			case ID_REMOTE_CONNECTION_LOST:
				m_pConfigDialog->UpdateServerLog("Another client has lost the connection.\n");
				break;
			case ID_REMOTE_NEW_INCOMING_CONNECTION:
				m_pConfigDialog->UpdateServerLog("Another client has connected.\n");
				break;
			case ID_CONNECTION_REQUEST_ACCEPTED:
				m_pConfigDialog->UpdateServerLog("Our connection request has been accepted.\n");
				break;
			case ID_NEW_INCOMING_CONNECTION:
				m_pConfigDialog->UpdateServerLog("A connection is incoming.\n");
				break;
			case ID_NO_FREE_INCOMING_CONNECTIONS:
				m_pConfigDialog->UpdateServerLog("The server is full.\n");
				break;
			case ID_DISCONNECTION_NOTIFICATION:
				m_pConfigDialog->UpdateServerLog("A client has disconnected.\n");
				break;
			case ID_CONNECTION_LOST:
				m_pConfigDialog->UpdateServerLog("A client lost the connection.\n");
				break;
			default:
				m_pConfigDialog->UpdateServerLog("Message with identifier %i has arrived.\n");
				break;
			}

			m_pServer->DeallocatePacket(packet);
		}
	}
}

bool CServer::RunServer(int port)
{
	bool bRet;

	// create the receive object
	

	m_pServer = RakNetworkFactory::GetRakPeerInterface();
	bRet = m_pServer->Startup(MAX_CLIENTS, 30, &SocketDescriptor(port,0), 1);

	// create a listener thread to listen on the port
	m_pPollThread = SDL_CreateThread(&server_thread_func,this);

	// set max connections for Raknet 
	m_pServer->SetMaximumIncomingConnections(MAX_CLIENTS);	

	if(bRet)
		m_pConfigDialog->UpdateServerLog("Server started.\n");

	m_bServerstarted = bRet;
	return bRet;
}

